package com.smarthome.common.tools.excel;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

/**
 * <p>
 * 导出表单
 * </p>
 * 
 */

public class ReportExportService extends AbstractReport {

    /**
     * 导出需要的excel表单
     * @param title 表格名称
     * @param headerNames 表头
     * @param cellNames 表头对应数据中的属性名
     * @param datas 表格数据
     * @param output 输出流
     * @author KongXiangyu
     */
    private void doExport(String title, List<String> headerNames, List<String> cellNames, List<Object> datas, OutputStream output) {
        this.tableHeaders = headerNames;
        this.cells = cellNames;
        ReportHeader reportHeader = HeaderUtil.getInstance().getReportHeader(title);
        export(reportHeader, datas, output);
    }

    public void doExportAndDownload(String fileName, String title, List<String> headerNames, List<String> cellNames, List<Object> datas, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Type", "application/force-download");
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        response.setContentType("application/vnd.ms-excel");
        String tempFileName = "下载文件";
        if (!StringUtils.isEmpty(fileName))
            tempFileName = fileName;
        response.setHeader("Content-disposition", "attachment; filename=" + new String(tempFileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
        doExport(title, headerNames, cellNames, datas, response.getOutputStream());
    }

    public void doExportAndDownload(String title, List<String> headerNames, List<String> cellNames, List<Object> datas, HttpServletResponse response) throws IOException {
        doExportAndDownload(title, title, headerNames, cellNames, datas, response);
    }

    // 表头
    private List<String> tableHeaders = new ArrayList<String>();
    // 列名
    private List<String> cells = new ArrayList<String>();

    /*
     * (non-Javadoc)
     * @see com.smarthome.common.tools.excel.AbstractReport#getCellNumber()
     */
    protected int getCellNumber() {
        return (int) tableHeaders.size();
    }

    /*
     * (non-Javadoc)
     * @see com.smarthome.common.tools.excel.AbstractReport#getCells()
     */
    protected List<String> getCells() {
        return cells;
    }

    /*
     * (non-Javadoc)
     * @see com.smarthome.common.tools.excel.AbstractReport#getTableHeader()
     */
    protected List<String> getTableHeader() {
        return tableHeaders;
    }

}